package com.zj.leetcode.easy.listNode;

/**
 * @program: algorithm
 * @description: 反转链表
 * 206 reverse-linked-list
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class ReverseLinkedList {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4,
                                        new ListNode(5, null)))));

        Solution solution = new ReverseLinkedList().new Solution();

        System.out.println(solution.reverseList02(listNode));
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }


    class Solution {
        public ListNode reverseList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }

            ListNode cur = head;
            while (cur.next != null) {
                ListNode next = cur.next;
                cur.next = cur.next.next;
                next.next = head;
                head = next;
            }

            return head;
        }

        public ListNode reverseList02(ListNode head) {
            return this.getOne(head);
        }

        public ListNode getOne(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            } else {
                ListNode last = this.getOne(head.next);
                head.next.next = head;
                head.next = null;
                return last;
            }
        }

        public ListNode reverseList03(ListNode head) {

            ListNode cur = head;
            ListNode per = null;
            while (cur != null){
                ListNode temp = cur.next;
                cur.next = per;
                per = cur;
                cur = temp;
            }
            return per;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
